package com.poetry.vup.common.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.poetry.vup.common.util.UidThreadLocal;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * 自定义填充公共 时间 字段
 *
 * @author mileswan
 */

@Component
public class TableMetaObjectHandler implements MetaObjectHandler {
    private final static String UPDATE_TIME = "gmtModified";
    private final static String CREATE_TIME = "gmtCreate";
    private final static String CREATE_UID = "createUser";
    private final static String UPDATE_UID = "modifiedUser";

    /**
     * 插入填充，字段为空自动填充
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        Object createTime = getFieldValByName(CREATE_TIME, metaObject);
        Object updateTime = getFieldValByName(UPDATE_TIME, metaObject);
        
        if (createTime == null) {
            setFieldValByName(CREATE_TIME, getDateValue(metaObject.getSetterType(CREATE_TIME)), metaObject);
        }
        if (updateTime == null) {
            setFieldValByName(UPDATE_TIME, getDateValue(metaObject.getSetterType(UPDATE_TIME)), metaObject);
        }
        
        // 设置后台用户id字段值
        /*Long currUid = UidThreadLocal.get();
        if(currUid != null && currUid > 0) {
        	Object createUid = getFieldValByName(CREATE_UID, metaObject);
            Object updateUid = getFieldValByName(UPDATE_UID, metaObject);
        	if(createUid == null) {
        		setFieldValByName(CREATE_UID, currUid, metaObject);
            }
        	if(updateUid == null) {
        		setFieldValByName(UPDATE_UID, currUid, metaObject);
            }
        }*/
        
    }

    /**
     * 更新填充
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        //mybatis-plus版本2.0.9+
        setFieldValByName(UPDATE_TIME, getDateValue(metaObject.getSetterType(UPDATE_TIME)), metaObject);
        
        // 设置后台用户id字段值
        /*Long currUid = UidThreadLocal.get();
        if(currUid != null && currUid > 0) {
            Object updateUid = getFieldValByName(UPDATE_UID, metaObject);
        	if(updateUid == null) {
        		setFieldValByName(UPDATE_UID, currUid, metaObject);
            }
        }*/
    }
    
    private Object getDateValue(Class<?> setterType) {
        if (Date.class.equals(setterType)) {
            return new Date();
        } else if (LocalDateTime.class.equals(setterType)) {
            return LocalDateTime.now();
        } else if (Long.class.equals(setterType)){
            return System.currentTimeMillis();
        }
        return null;
    }

}